import { routeManager } from './routeManager';

/**
 * 路由刷新工具
 * 用于处理菜单权限变化时的路由更新
 */
export class RouteRefreshManager {
  private static instance: RouteRefreshManager;
  private refreshCallbacks: Set<() => void> = new Set();
  private isRefreshing = false;

  private constructor() {
    this.setupEventListeners();
  }

  public static getInstance(): RouteRefreshManager {
    if (!RouteRefreshManager.instance) {
      RouteRefreshManager.instance = new RouteRefreshManager();
    }
    return RouteRefreshManager.instance;
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners(): void {
    // 监听用户权限变化事件
    window.addEventListener('userPermissionChanged', this.handlePermissionChange.bind(this));
    
    // 监听菜单更新事件
    window.addEventListener('menuUpdated', this.handleMenuUpdate.bind(this));
    
    // 监听角色变化事件
    window.addEventListener('userRoleChanged', this.handleRoleChange.bind(this));
  }

  /**
   * 处理权限变化
   */
  private async handlePermissionChange(): Promise<void> {
    console.log('检测到用户权限变化，准备刷新路由');
    await this.refreshRoutes();
  }

  /**
   * 处理菜单更新
   */
  private async handleMenuUpdate(): Promise<void> {
    console.log('检测到菜单更新，准备刷新路由');
    await this.refreshRoutes();
  }

  /**
   * 处理角色变化
   */
  private async handleRoleChange(): Promise<void> {
    console.log('检测到用户角色变化，准备刷新路由');
    await this.refreshRoutes();
  }

  /**
   * 刷新路由
   */
  public async refreshRoutes(): Promise<void> {
    if (this.isRefreshing) {
      console.log('路由刷新正在进行中，跳过本次刷新');
      return;
    }

    try {
      this.isRefreshing = true;
      
      // 清除路由管理器缓存
      routeManager.clearCache();
      
      // 触发所有注册的刷新回调
      this.refreshCallbacks.forEach(callback => {
        try {
          callback();
        } catch (error) {
          console.error('路由刷新回调执行失败:', error);
        }
      });
      
      console.log('路由刷新完成');
    } catch (error) {
      console.error('路由刷新失败:', error);
    } finally {
      this.isRefreshing = false;
    }
  }

  /**
   * 注册刷新回调
   */
  public onRefresh(callback: () => void): () => void {
    this.refreshCallbacks.add(callback);
    
    // 返回取消注册的函数
    return () => {
      this.refreshCallbacks.delete(callback);
    };
  }

  /**
   * 触发权限变化事件
   */
  public triggerPermissionChange(): void {
    window.dispatchEvent(new CustomEvent('userPermissionChanged'));
  }

  /**
   * 触发菜单更新事件
   */
  public triggerMenuUpdate(): void {
    window.dispatchEvent(new CustomEvent('menuUpdated'));
  }

  /**
   * 触发角色变化事件
   */
  public triggerRoleChange(): void {
    window.dispatchEvent(new CustomEvent('userRoleChanged'));
  }

  /**
   * 强制刷新页面（最后的手段）
   */
  public forceRefresh(): void {
    console.log('执行强制页面刷新');
    window.location.reload();
  }

  /**
   * 检查是否需要刷新路由
   */
  public async checkNeedRefresh(): Promise<boolean> {
    try {
      // 获取当前缓存的菜单
      const cachedMenus = await routeManager.getUserMenus();
      
      // 强制获取最新菜单
      const latestMenus = await routeManager.getUserMenus(true);
      
      // 比较菜单是否有变化
      return JSON.stringify(cachedMenus) !== JSON.stringify(latestMenus);
    } catch (error) {
      console.error('检查路由刷新需求失败:', error);
      return false;
    }
  }

  /**
   * 定期检查路由是否需要更新
   */
  public startPeriodicCheck(interval: number = 30000): () => void {
    const checkInterval = setInterval(async () => {
      try {
        const needRefresh = await this.checkNeedRefresh();
        if (needRefresh) {
          console.log('定期检查发现菜单变化，刷新路由');
          await this.refreshRoutes();
        }
      } catch (error) {
        console.error('定期路由检查失败:', error);
      }
    }, interval);

    // 返回停止检查的函数
    return () => {
      clearInterval(checkInterval);
    };
  }

  /**
   * 获取刷新状态
   */
  public isCurrentlyRefreshing(): boolean {
    return this.isRefreshing;
  }

  /**
   * 清理资源
   */
  public cleanup(): void {
    this.refreshCallbacks.clear();
    window.removeEventListener('userPermissionChanged', this.handlePermissionChange.bind(this));
    window.removeEventListener('menuUpdated', this.handleMenuUpdate.bind(this));
    window.removeEventListener('userRoleChanged', this.handleRoleChange.bind(this));
  }
}

// 导出单例实例
export const routeRefreshManager = RouteRefreshManager.getInstance();

// 导出便捷方法
export const refreshRoutes = () => routeRefreshManager.refreshRoutes();
export const triggerPermissionChange = () => routeRefreshManager.triggerPermissionChange();
export const triggerMenuUpdate = () => routeRefreshManager.triggerMenuUpdate();
export const triggerRoleChange = () => routeRefreshManager.triggerRoleChange();